'use strict';

export default class extends think.Controller {
  
	//初始化操作
	async __before(){

		//进行登陆判断
		let is_login = await this.is_login();
		if(!is_login){
			return this.fail('请重新登陆！');
		}		
		this.shop_userinfo = await this.session('shop_userinfo');
		if(!this.shop_userinfo.headimg){
			this.shop_userinfo.headimg = this.config('HEAD_IMG');
		}	
		//跨域全局设置
		this.setCors();

	}
	
	
	//判断是否登陆   	
	async is_login(){
		// 通过token判断是否登录
		let token = this.header('token')
		if (!token) {
			return false
		} else {
			// 验证token是否有效（解码token）
			token = new Buffer(token, 'base64').toString()
			const S = require('../login/secret.js')
			let secret = new S()
			token = token.split('.')
			let url = this.ctx.request.url
			let index = url.indexOf('?')
			if (index > -1) {
				url = url.substr(0, index)
			}
			if (token[3] != '/' + url.split('/').slice(3).join('/')) {
				return false
			}
			if (secret.createHmac(token[0] + '.' + token[1]) == token[2]) {
				let specialSecret = secret.decipherbase64(token[1])
				let userinfo = await this.model('or_admin').where({id: specialSecret.uid}).find()
				await this.session('shop_userinfo',userinfo)
				return userinfo.id
			} else {
				return false
			}
		}
	}
	
	
	//更新用户session
	async update_session(){
		let is_login = await this.is_login();
		if(is_login){
			let userinfo = await this.model('or_admin').where({id:is_login}).find();
			await this.session('shop_userinfo',userinfo);
			return true;
		}else{
			return false;
		}	
	}
	
	setCors(){ 
		let method = this.userAgent.toLowerCase();
		if(method === "options"){
			this.setCorsHeader();
			this.end();
			return;
    	} 
		this.setCorsHeader();
  	}
  	setCorsHeader(){
		this.header("Access-Control-Allow-Origin", this.header("origin") || "*");
		this.header("Access-Control-Allow-Headers", "x-requested-with");
		this.header("Access-Control-Request-Method", "GET,POST,PUT,DELETE");
		this.header("Access-Control-Allow-Credentials", "true");
  	}



	//获取订单编号
	async getordersn(headstr,type){
		//查询该店有没有该单号的num没有新增，日期不是今天重置日期和num，有的话num+1
		let nowdate = new Date();
		let datemonth = nowdate.getMonth();
		let dateday = nowdate.getDate();
		datemonth += 1;
		datemonth = datemonth<10?'0'+datemonth:datemonth;
		dateday = dateday<10?'0'+dateday:dateday;
		let today = nowdate.getFullYear()+'-'+datemonth+'-'+dateday;
		let isexist = await this.model('or_autonum')
			.where({departmentid:this.shop_userinfo.departmentid,shortorder:headstr})
			.find();	
		let dataarr,res;
		if(think.isEmpty(isexist) || isexist.addtime != today){
			dataarr = {
				"departmentid":this.shop_userinfo.departmentid,
				"adminid":this.shop_userinfo.id,
				"addtime":today,
				"num":1,
				"type":type,
				"shortorder":headstr,
				"id":isexist.id,
			}
			if (isexist.id) {
				res = await this.model('or_autonum').where({id: isexist.id}).update(dataarr);
			} else {
				res = await this.model('or_autonum').add(dataarr);
			}
		}else {
			dataarr = {
				"num":isexist.num+1,
			}
			res = await this.model('or_autonum')
				.where({departmentid:this.shop_userinfo.departmentid,shortorder:headstr})
				.update(dataarr);
		}
		let snnum = '00000'+dataarr.num;
		snnum = headstr+today+'-'+snnum.substring(snnum.length-5,snnum.length);
		return res?snnum:this.fail('生成订单号失败！');
	}
}